import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {ProTable} from '@ant-design/pro-components';
import {Button, Form, Input, message, Radio, Switch, Tag} from 'antd';
import {getUserById, listUserByPage, updateUserRole, updateUserStatus} from '@/services/ant-design-pro/userController';
import ModalWrapper from '@/components/ModalWrapper';

const UserManagement: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [roleModalVisible, setRoleModalVisible] = useState<boolean>(false);
  const [currentUserId, setCurrentUserId] = useState<number>(0);
  const [roleForm] = Form.useForm();
  const [statusForm] = Form.useForm();
  const [statusModalVisible, setStatusModalVisible] = useState<boolean>(false);

  // 用户角色枚举
  const userRoles: Record<number, { text: string; color: string }> = {
    0: {text: '普通用户', color: 'blue'},
    1: {text: '管理员', color: 'red'},
  };

  // 用户状态枚举
  const userStatus: Record<number, { text: string; color: string }> = {
    0: {text: '禁用', color: 'default'},
    1: {text: '正常', color: 'success'},
  };

  // 打开修改角色对话框
  const handleOpenRoleModal = async (userId: number) => {
    setCurrentUserId(userId);
    try {
      const res = await getUserById({id: userId});
      if (res.data) {
        roleForm.setFieldsValue({role: res.data.role || 0});
      }
    } catch (error) {
      message.error('获取用户信息失败');
    }
    setRoleModalVisible(true);
  };

  // 确认修改角色
  const handleRoleOk = async () => {
    try {
      const values = await roleForm.validateFields();
      const res = await updateUserRole({
        userId: currentUserId,
        role: values.role,
        remark: values.remark || '',
      });

      if (res.code === 0 && res.data) {
        message.success('用户角色更新成功');
        setRoleModalVisible(false);
        actionRef.current?.reload();
      } else {
        message.error('用户角色更新失败');
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 打开修改状态对话框
  const handleOpenStatusModal = async (userId: number) => {
    setCurrentUserId(userId);
    try {
      const res = await getUserById({id: userId});
      if (res.data) {
        statusForm.setFieldsValue({enabled: res.data.role === 1 ? 1 : 0});
      }
    } catch (error) {
      message.error('获取用户信息失败');
    }
    setStatusModalVisible(true);
  };

  // 确认修改状态
  const handleStatusOk = async () => {
    try {
      const values = await statusForm.validateFields();
      const res = await updateUserStatus({
        userId: currentUserId,
        enabled: values.enabled,
        remark: values.remark || '',
      });

      if (res.code === 0 && res.data) {
        message.success('用户状态更新成功');
        setStatusModalVisible(false);
        actionRef.current?.reload();
      } else {
        message.error('用户状态更新失败');
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 切换用户状态
  const handleToggleStatus = async (checked: boolean, userId: number) => {
    try {
      const res = await updateUserStatus({
        userId,
        enabled: checked ? 1 : 0,
        remark: '管理员操作',
      });

      if (res.code === 0 && res.data) {
        message.success(`用户已${checked ? '启用' : '禁用'}`);
        actionRef.current?.reload();
      } else {
        message.error('操作失败');
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 表格列定义
  const columns: ProColumns<API.UserVO>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      search: false,
    },
    {
      title: '账号',
      dataIndex: 'account',
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      search: {},
      fieldProps: {
        placeholder: '请输入邮箱',
      },
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      search: {},
      fieldProps: {
        placeholder: '请输入手机号',
      },
    },
    {
      title: '角色',
      dataIndex: 'role',
      valueEnum: userRoles,
      render: (_, record) => (
        <Tag color={userRoles[record.role || 0]?.color}>
          {userRoles[record.role || 0]?.text}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      valueEnum: userStatus,
      render: (_, record) => (
        <Switch
          checked={record.role === 1}
          onChange={(checked) => handleToggleStatus(checked, record.id!)}
        />
      ),
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <Button
          key="edit-role"
          type="link"
          onClick={() => handleOpenRoleModal(record.id!)}
        >
          修改角色
        </Button>,
        <Button
          key="edit-status"
          type="link"
          onClick={() => handleOpenStatusModal(record.id!)}
        >
          详细设置
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '用户管理',
      }}
    >
      <ProTable<API.UserVO, API.UserPageQueryDTO>
        headerTitle="用户列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        request={async (params, sorter, filter) => {
          const {current, pageSize, ...restParams} = params;
          try {
            const res = await listUserByPage({
              current,
              pageSize,
              ...restParams,
            });

            return {
              data: res.data?.records || [],
              success: res.code === 0,
              total: res.data?.total || 0,
            };
          } catch (error) {
            message.error('获取用户列表失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
      />

      {/* 修改角色对话框 */}
      <ModalWrapper
        title="修改用户角色"
        visible={roleModalVisible}
        onOk={handleRoleOk}
        onCancel={() => setRoleModalVisible(false)}
      >
        <Form form={roleForm} layout="vertical">
          <Form.Item
            name="role"
            label="用户角色"
            rules={[{required: true, message: '请选择用户角色'}]}
          >
            <Radio.Group>
              <Radio value={0}>普通用户</Radio>
              <Radio value={1}>管理员</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="remark"
            label="操作备注"
          >
            <Input.TextArea rows={3} placeholder="请输入修改原因"/>
          </Form.Item>
        </Form>
      </ModalWrapper>

      {/* 修改状态对话框 */}
      <ModalWrapper
        title="修改用户状态"
        visible={statusModalVisible}
        onOk={handleStatusOk}
        onCancel={() => setStatusModalVisible(false)}
      >
        <Form form={statusForm} layout="vertical">
          <Form.Item
            name="enabled"
            label="用户状态"
            rules={[{required: true, message: '请选择用户状态'}]}
          >
            <Radio.Group>
              <Radio value={0}>禁用</Radio>
              <Radio value={1}>启用</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="remark"
            label="操作备注"
          >
            <Input.TextArea rows={3} placeholder="请输入修改原因"/>
          </Form.Item>
        </Form>
      </ModalWrapper>
    </PageContainer>
  );
};

export default UserManagement;
